<?php

namespace App\Modules\Apicrzs\Services\Public;


use App\Exceptions\Exception;
use App\Modules\Apicrzs\Entities\UsersModel;
use App\Modules\Apicrzs\Services\BaseServices;

use EasyWeChat\MiniApp\Application;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;


class LoginWxService extends BaseServices
{
    public function __construct(UsersModel $model)
    {
        $this->model = $model;
    }
    /**
     * 静默登录，获取微信用户openid，后续与用户表绑定，并生成token。
     * @param $code
     * @return array|void
     * @throws Exception
     */
    public function silenceAuth($params){

        $wechat = Config::get('wechat')['MiniApp'];

        $code = $params['code'];
        $spread_spid = $params['spread_spid'];

        $app = new Application(getWxConfig('MiniApp'));
        return $app->getUtils()->codeToSession($code);

    }

    public function authType($params){

        $code = $params['code'];
        $spread_spid = $params['spread_spid'];
        $config = [
            'app_id' => config('services.wechat.mini_program.app_id'),
            'secret' => config('services.wechat.mini_program.secret'),
        ];
        $app = new Application($config);

        return $app->getUtils()->codeToSession($code);


    }

    public function authBindingPhone($params)
    {

        $code = $params['code'];
        $iv = $params['iv'];
        $sessionKey = $params['key'];
        $encryptedData = $params['encryptedData'];
        $spread_code = $params['spread_code']??'';
        $spread_spid = $params['spread_spid']??'';

        if (!$code || !$iv || !$encryptedData)
            return app('json')->fail(100100);
        $config = [
            'app_id' => config('services.wechat.mini_program.app_id'),
            'secret' => config('services.wechat.mini_program.secret'),
        ];
        $app = new Application($config);
        $utils = $app->getUtils();
        $response = $utils->codeToSession($code);
        $session = $utils->decryptSession($sessionKey, $iv, $encryptedData);


        exit(json_encode($session)) ;
    }
}
